#include "videohandler.h"
#include <QCameraDevice>
#include <QMediaDevices>
#include <QMessageBox>
#include <QMediaCaptureSession>
#include <QDebug>

VideoHandler::VideoHandler(QObject *parent)
    : QObject{parent}
{
    initCamera();
}

VideoHandler::~VideoHandler()
{
    qDebug() << "call delete videoHandler";
    if (m_camera)
    {
        qDebug() << "stop camera";
        m_camera->stop();
    }
}


// 打开、关闭摄像头
void VideoHandler::onChangeCameraStatus(bool status)
{
    if (!m_camera)
    {
        qDebug() << "camera does not exist";
        return;
    }
    if (status)
    {
        m_camera->start();
    }
    else
    {
        m_camera->stop();
    }
}


// 切换摄像头
void VideoHandler::onChangeCamera(const QCameraDevice cameraDevice)
{
    bool originStatus = false;
    if (m_camera && m_camera->isActive()) {
        originStatus = true;
        m_camera->stop();
        m_camera->setCameraDevice(cameraDevice);
        qDebug() << "成功切换摄像头为" << cameraDevice;
    }
    if (originStatus)
    {
        m_camera->start();
    }
}

// 初始化摄像头
void VideoHandler::initCamera()
{
    //获取默认摄像头
    QCameraDevice defaultCameraDevice = QMediaDevices::defaultVideoInput();
    if(defaultCameraDevice.isNull()){
        emit initStatus(false);
        return;
    }
    //初始化摄像头对象
    m_camera = new QCamera(this);
    m_camera->setCameraDevice(defaultCameraDevice);

    // 创建捕获会话
    QMediaCaptureSession* m_captureSession = new QMediaCaptureSession(this);
    m_captureSession->setCamera(m_camera);

    // 创建视频接收器（但不显示）
    m_videoSink = new QVideoSink(this);
    m_captureSession->setVideoSink(m_videoSink);

    // 摄像头启动就发给ImageDealer处理
    connect(m_videoSink, &QVideoSink::videoFrameChanged, this, [=](const QVideoFrame &frame){
        // qDebug() << "发图片给ImageDealer处理";
        emit frameReadyToDeal(frame.toImage());
    });


}
